<template>
  <div>

    <!--用户列表卡片-->
    <el-card class="box-card">
      <!--搜索，添加等-->
      <el-form :inline="true" :model="userVo" class="demo-form-inline">
        <el-form-item label="部门" label-width="70px">
          <el-select clearable @clear="search" v-model="userVo.departmentId" placeholder="请选择" value="">
            <el-option
              v-for="item in departments"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              @click.native="search">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                <span class="el-tag el-tag--success el-tag--mini el-tag--plain">{{ item['deptCount'] }}</span>
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" label-width="70px">
          <el-select clearable @clear="search" v-model="userVo.roleId" placeholder="请选择" value="">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
              @click.native="search">
              <span style="float: left">{{ item.roleName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" label-width="70px">
          <el-input clearable="" @keyup.enter.native="search" @clear="search" v-model="userVo.username"
                    placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="70px">
          <el-input clearable="" @keyup.enter.native="search" @clear="search" v-model="userVo.email"
                    placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label-width="70px">
          <el-radio-group v-model="userVo.sex" @change="search">
            <el-radio label="0">男</el-radio>
            <el-radio label="1">女</el-radio>
            <el-radio label="2">保密</el-radio>
            <el-radio label="">全部</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="昵称" label-width="70px">
          <el-input clearable="" @keyup.enter.native="search" @clear="search" v-model="userVo.nickname"
                    placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item style="margin-left: 10px">
          <el-button icon="el-icon-refresh" @click="resetUserVo">重置</el-button>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
          <el-button type="success" icon="el-icon-plus" @click="openAdd">添加</el-button>
          <el-button type="warning" icon="el-icon-download" @click="downExcel">导出</el-button>
          <el-button icon="el-icon-delete" @click="deleteUsers" :disabled="this.select.length === 0">批删</el-button>
        </el-form-item>
      </el-form>

      <!--表格内容显示区-->
      <el-table
        :data="userList"
        border
        max-height="400"
        style="width: 100%"
        @selection-change="selectChange">
        <el-table-column
          type="selection"
          header-align="center"
          align="center"
          width="40"
          :selectable="selectable">
        </el-table-column>
        <el-table-column
          prop="id"
          fixed="left"
          align="center"
          header-align="center"
          label="#"
          width="50">
        </el-table-column>
        <el-table-column
          prop="username"
          fixed="left"
          header-align="center"
          align="center"
          label="用户名"
          width="120">
        </el-table-column>
        <el-table-column
          prop="nickname"
          header-align="center"
          align="center"
          label="昵称"
          width="120">
        </el-table-column>
        <el-table-column
          prop="sex"
          header-align="center"
          align="center"
          label="性别"
          width="60">
          <template slot-scope="scope">
            {{scope.row.sex===0?'男':(scope.row.sex===1)?'女':'保密'}}
          </template>
        </el-table-column>
        <el-table-column
          prop="deptName"
          header-align="center"
          align="center"
          label="所属部门"
          width="150">
        </el-table-column>
        <el-table-column
          sortable=""
          prop="birth"
          header-align="center"
          align="center"
          label="生日"
          width="150">
          <template slot-scope="scope">
            {{scope.row.birth}}
          </template>
        </el-table-column>
        <el-table-column
          prop="email"
          header-align="center"
          align="center"
          label="邮箱"
          width="180">
        </el-table-column>
        <el-table-column
          prop="phoneNumber"
          header-align="center"
          align="center"
          label="电话号码"
          width="150">
        </el-table-column>
        <el-table-column
          prop="createTime"
          header-align="center"
          align="center"
          label="创建时间"
          width="170">
        </el-table-column>
        <el-table-column
          prop="modifiedTime"
          header-align="center"
          align="center"
          label="修改时间"
          width="170">
        </el-table-column>
        <el-table-column
          prop="status"
          label="是否可用"
          fixed="right"
          header-align="center"
          align="center"
          width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              :disabled="scope.row.username === loginUser.username"
              @change="changUserStatus(scope.row)"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          header-align="center"
          align="center"
          fixed="right"
          width="180">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit"
                       @click="openUpdate(scope.row)"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete"
                       @click="handleDelete(scope.row)"></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-s-tools"
                @click="assignRoles(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <el-pagination
        style="padding-top: 15px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[6, 10, 20, 30]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

      <UserAdd :addVisible="addVisible"
               :departments="departments"
               @changeShow="showAdd"
               @reFresh="reFresh">
      </UserAdd>

      <UserUpdate :updateUser="this.updateUser"
                  :updateVisible="updateVisible"
                  :departments="departments"
                  @changeShow="showUpdate"
                  @reFresh="reFresh">
      </UserUpdate>

      <!-- 分配角色对话框 -->
      <el-dialog :modal-append-to-body="false" center="" title="分配角色" :visible.sync="assignDialogVisible" width="49%">
              <span>
                <template>
                  <el-transfer
                    filterable
                    :titles="['未拥有','已拥有']"
                    :button-texts="['到左边', '到右边']"
                    v-model="value"
                    :data="roles"
                  ></el-transfer>
                </template>
              </span>
        <span slot="footer" class="dialog-footer">
                <el-button @click="assignDialogVisible = false" class="el-icon-close">取消分配</el-button>
                <el-button
                  type="primary"
                  @click="doAssignRoles"
                  class="el-icon-check"
                  :loading="btnLoading"
                  :disabled="btnDisabled"
                >确定分配</el-button>
              </span>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
  import { findDeptAndCount } from '../../../api/system/dept'
  import {
    deleteUserById, deleteUsersByIds,
    findUserList, downUserExcel, getUserRoles, assignRoles, updateStatus
  } from '../../../api/system/users'
  import { deleteFile, deleteFiles } from '../../../api/system/aliOss'
  import { deleteFileByUrl, deleteFilesByUrls } from '../../../api/system/file'

  import UserAdd from './UserAdd'
  import UserUpdate from './UserUpdate'
  import { getRoleList } from '../../../api/system/roles'

  export default {
    name: 'Users',

    data () {
      return {
        btnLoading: false,
        btnDisabled: false,
        select: [], //选中的值显示
        updateUser: '',
        loginUser: JSON.parse(window.sessionStorage.getItem('userInfo')),
        addVisible: false,
        updateVisible: false,
        assignDialogVisible: false, //分配角色对话框
        roles: [], //角色
        value: [], //用户拥有的角色
        uid: '',//当前分配角色的用户id
        userVo: {
          roleId: '',
          departmentId: '',
          username: '',
          email: '',
          sex: '',
          nickname: ''
        },
        userList: [],
        roleList: [],
        deptList: [],
        user: {},
        size: 6,
        total: 100,
        current: 1,
        departments: []
      }
    },
    components: {
      UserAdd,
      UserUpdate
    },
    created () {
      //创建组件时调用方法
      this.reFresh()
      this.getRoleList()
    },
    methods: {
      //多选框发生变化
      selectChange (sels) {
        this.select = sels
      },

      //禁用表格中当前用户行的多选框
      selectable (row) {
        return row.username !== this.loginUser.username
      },
      //获取所有角色
      getRoleList () {
        getRoleList().then(res => {
          if (res) {
            this.roleList = res.data.data.records
          }
        })
      },

      //批量删除用户
      async deleteUsers () {
        const ids = this.select.map(item => item.id).join() //获取所有选中行的id组成的字符串，以逗号分隔
        const urls = this.select.map(item => item.avatar).join() //获取所有选中行的url组成的字符串，以逗号分隔
        const res = await this.$confirm(
          '是否删除这' + this.select.length + '位用户?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
        if (res === 'confirm') {
          const { data: res } = await deleteUsersByIds(ids)
          const { data: res1 } = await deleteFilesByUrls(urls)
          const { data: res2 } = await deleteFiles(urls)
          if (res.code === 200 && res1.code === 200 && res2.code === 200) {
            console.log(res1, res2)
            this.$message.success('用户删除成功')
            this.reFresh()
          } else {
            this.$message.error(res.msg)
          }
        }
      },

      //删除操作
      handleDelete: function (row) {
        this.$confirm('删除操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteUser(row.id, row.avatar)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },

      //当每页条数改变
      handleSizeChange (val) {
        this.size = val
        this.getUserList()
      },

      //当前页码改变
      handleCurrentChange (val) {
        this.current = val
        this.getUserList()
      },

      //获得当前页面数据
      async getUserList () {
        findUserList(this.current, this.size, this.userVo).then(res => {
          if (res) {
            this.userList = res.data.data.records
            this.total = res.data.data.total
          }
        })
      },

      //获得部门信息
      getDeptAndCount () {
        findDeptAndCount().then(res => {
          if (res) {
            this.departments = res.data.data.departments
          }
        })
      },

      //删除用户阿里云中的头像
      async deleteAvatar (oldImg) {
        await deleteFile(oldImg)
      },

      //删除用户
      async deleteUser (id, avatar) {
        await deleteUserById(id).then(res => {
          if (res) {
            this.deleteAvatar(avatar)
            this.deleteFileInMysql(avatar)
            this.$notify.success({
              title: '操作成功',
              message: '用户删除',
            })
            //刷新数据
            this.reFresh()
          }
        })
      },

      //删除数据库里的文件记录
      async deleteFileInMysql (oldImg) {
        await deleteFileByUrl(oldImg)
      },

      /**
       * 弹出用户分配角色
       */
      async assignRoles (id) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        getUserRoles(id).then(res => {
          if (res) {
            this.roles = res.data.data.roles
            this.value = res.data.data.values
            this.uid = id

            setTimeout(() => {
              loading.close()
              this.assignDialogVisible = true
            }, 400)
          }
        })
      },
      /**
       * 确定分配角色
       */
      async doAssignRoles () {
        this.assignDialogVisible = true
        this.btnLoading = true
        this.btnDisabled = true
        assignRoles(this.uid, this.value).then(res => {
          if (res) {
            this.$notify.success({
              title: '操作成功',
              message: '用户分配角色成功',
            })
          }
        })
        this.assignDialogVisible = false
        this.btnLoading = false
        this.btnDisabled = false
      },

      //改变用户状态
      async changUserStatus (row) {
        try {
          updateStatus(row.id, row.status).then(res => {
            if (res) {
              const message = row.status ? '用户状态:已启用' : '用户状态:已禁用'
              this.$notify.success({
                title: '操作成功',
                message: message,
              })
              this.getUserList()
            }
          })
        } catch (e) {
          row.status = row.status ? 0 : 1
        }
      },

      //搜索
      search () {
        this.current = 1
        this.reFresh()
      },

      //刷新页面
      reFresh () {
        this.getUserList()
        this.getDeptAndCount()
      },

      //重置表单
      resetUserVo () {
        this.userVo.roleId = ''
        this.userVo.departmentId = ''
        this.userVo.username = ''
        this.userVo.email = ''
        this.userVo.sex = ''
        this.userVo.nickname = ''
        this.reFresh()
      },

      // 按钮点击事件 显示新增编辑弹窗组件
      openAdd () {
        this.addVisible = true
      },

      //导出用户Excel
      downExcel () {
        downUserExcel()
          .then(res => {
            const data = res.data
            let url = window.URL.createObjectURL(data) // 将二进制文件转化为可访问的url
            const a = document.createElement('a')
            document.body.appendChild(a)
            a.href = url
            a.download = '用户列表.xls'
            a.click()
            window.URL.revokeObjectURL(url)
          })
      },

      // 按钮点击事件 显示编辑弹窗组件
      openUpdate: function (row) {
        //对象深克隆
        row = JSON.parse(JSON.stringify(row))
        this.updateUser = row
        this.updateVisible = true
      },

      // 监听 子组件弹窗关闭后触发，有子组件调用
      showAdd (data) {
        this.addVisible = data !== 'false'
      },
      // 监听 子组件弹窗关闭后触发，有子组件调用
      showUpdate (data) {
        this.updateVisible = data !== 'false'
      }
    }
  }
</script>

<style scoped>

</style>
